package org.example.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 *  JWT token
 */
public class JWTUtil {
    static String MHAC256 = "secret";
    static String ISSUER = "mjl416";

    /**
     * create JWT token
     */
    public static String create(String key,String value){
        String token = null;
        try {
            Algorithm algorithm = Algorithm.HMAC256(MHAC256);
            token = JWT.create().
                    //头部header
                    withIssuer(ISSUER).
                    //签发时间
                    withIssuedAt(new Date()).
                    //失效时间
                    withExpiresAt(new Date(System.currentTimeMillis()+300000000)).
                    withClaim(key,value).
                    //电子签名
                    sign(algorithm);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }

    /**
     * verify JWT token
     */
    public static boolean verify(String token){
        boolean flag = true;
        try {
            Algorithm algorithm = Algorithm.HMAC256(MHAC256);
            JWTVerifier verifier = JWT.require(algorithm).withIssuer(ISSUER).build();
            DecodedJWT verify = verifier.verify(token);//验证token
        } catch (Exception e) {
            flag = false;
        }
        return flag;
    }

    public static void main(String[] args) {
//        String s = create();
//        System.out.println(s);
        System.out.println(verify("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"));
    }
}
